package org.jxy.study.rpc.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author : porteryao
 * @description : Json工具类
 * @date : 2021/3/12 14:03
 */
public class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象转为Json字符串
     */
    public static String objectToJsonString(Object o) {
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Json字符串转成对象
     *
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T jsonStringToObject(String str, Class<?> clazz) {
        try {
            return (T) mapper.readValue(str, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * byte数组转成对象
     *
     * @param data
     * @param clazz
     * @return T
     * @author jxy
     * @date 2021/3/12
     */
    public static <T> T bytesToObject(byte[] data, Class clazz) {
        try {
            return (T) mapper.readValue(data, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将对象转为字节数组
     *
     * @param object
     * @return byte[]
     */
    public static byte[] objectToJsonByteArray(Object object) {
        try {
            return mapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }
}
